// // pages/test1/1.js
let biaoti_flag = 0 //0表示默认2行，1表示3行
let shijian_flag = 0 //0表示默认1行，1表示1长数据
let Openid = ""
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _id: "",
    collected: false, //已收藏
    message_list: ''
  },

  addCollection() {
    var app = getApp();
    console.log(this.data._id)
    wx.$cloud.callFunction({
      name: "userModule",
      data: {
        action: "add_collection",
        openid: app.globalData.openId,
        newcollection: this.data._id,
        type: 2
      },
      success: res => {
        console.log(res, "添加成功")
      }
    })
  },

  deleteCollection() {
    var app = getApp();
    wx.$cloud.callFunction({
      name: "userModule",
      data: {
        action: "delete_collection",
        openid: app.globalData.openId,
        curr_id: this.data._id,
        type: 2
      },
      success: res => {
        console.log(res, "删除成功")
      }
    })
  },
  top_preview(options) {
    const that = this
    var current = options.target.dataset.url
    wx.previewImage({
      urls: that.data.message_list[0].pictures,
      current: current
    })
  },

  getopenid() {
    var that = this;

    wx.$cloud.callFunction({
      name: "getopenid",
      success(res) {
        console.log("获取openid成功1", res)
        console.log("获取openid成功2", res.result.openid)
        //  that.setData({
        //    Openid:res.result.openid
        //  })
        Openid = res.result.openid

      },
      fail(res) {
        console.log("获取openid失败", res)
      },
    })
  },


  Collect() {
    var that = this;
    wx.$cloud.callFunction({
      name: "getopenid",
      success(res) {
        console.log("获取openid成功1", res)
        console.log("获取openid成功2", res.result.openid)
        Openid = res.result.openid
        const db = wx.$cloud.database()
        db.collection("user").where({
          openid: Openid
        }).get().then(res => {
          console.log("wwwwwww", res.data)
          if (res.data.length) {
            if (that.data.collected) that.deleteCollection();
            else that.addCollection();
            var collected = !that.data.collected;
            that.setData({
              collected
            })
          } else {
            wx.showToast({
              title: '请先登录',
              icon: 'none'
            })
          }
        })


      },
      fail(res) {
        console.log("获取openid失败", res)
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
      },
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      _id: options._id
    })
    let that = this;
    console.log("这是", options._id)
    wx.$cloud.callFunction({
      name: "getIndexInfo",
      data: {
        action: "employ_notice",
        _id: this.data._id,
        // _id:"18ed0968619b4675069edff54b00fce0",
        sign: 19,
      }
    }, ).then(res => {
      console.log(res.result.data)
      // let temp_content = res.result.data.content
      // let temp_content_arr = temp_content.split('\n')
      // console.log("temp_content_arr",temp_content_arr)
      let temp = res.result.data
      let last = new Date(temp.date)
      let string_last = new Date(last).getFullYear() + '年' + (new Date(last).getMonth() + 1) + '月' + new Date(last).getDate() + '日';
      temp.time = string_last;
      let example0 = "香港中文大学（深圳）龙岗附属学校（教育集团）2021年下半年赴武汉面向毕业生"
      let example1 = "香港中文大学（深圳）龙岗附属学校（教育集团）2021年下半年赴武汉面向毕业生公开招聘教师公告公告公告公告"
      if (temp.title.length >= example0.length && temp.title.length <= example1.length) {
        console.log("hhhh")
        biaoti_flag = 1
        that.setData({
          biaoti_flag: 1
        })
      } else {
        console.log("qqqq")
        biaoti_flag = 0
        that.setData({
          biaoti_flag: 0
        })
      }

      let example3 = "香港中文大学（深圳）龙岗附属学"
      // let example3 = "香港中文大学（深圳）龙岗附属学"
      if (temp.apart.length >= example3.length) {
        console.log("2hhhh")
        shijian_flag = 1
        that.setData({
          shijian_flag: 1
        })
      } else {
        console.log("2qqqq")
        shijian_flag = 0
        that.setData({
          shijian_flag: 0
        })
      }
      if (temp.fujian_name) {
        let temp1 = temp.fujian_name.split('\n\n')
        let temp2 = []
        temp1.forEach(element => {
          temp2.push(element.replace(/(^\s*)|(\s*$)/g, ""))
        });
        temp.fujian_name = temp2
        console.log("--------temp:", temp1)
      }

      var length = temp.texts.length
      var contents = []
      for (let i = 0; i < length; i++) {
        let text = temp.texts[i]
        let picture = temp.pictures[i]
        if (picture == undefined) {
          picture = ""
        }
        contents.push([text, picture])
      }
      console.log("==========", contents)
      that.setData({
        message_list: [temp],
        contents: contents
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var app = getApp();
    wx.$cloud.callFunction({
      name: "userModule",
      data: {
        action: "ifCollected",
        openid: app.globalData.openId,
        currID: this.data._id,
        type: 2
      },
      success: res => {
        this.setData({
          collected: res.result
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "分享公告"
    }
  },

  //下载文件
  download: function (e) {
    //获取传递的链接id
    console.log("e:", e)
    var index = e.currentTarget.dataset.index
    //获取下载链接
    let url = this.data.message_list[0].files[index]
    let fileName = this.data.message_list[0].fujian_name[index];
    wx.downloadFile({
      url: url,
      success: function (res) {
        console.log(res);
        const manage = wx.getFileSystemManager();
        if (res.statusCode === 200) {
          console.log("temp:", res.tempFilePath)
          var x = res.tempFilePath.split(".")
          console.log("file:", x[x.length - 1])
          fileName = fileName + "." + x[x.length - 1]
          manage.saveFile({
            tempFilePath: res.tempFilePath,
            filePath: wx.env.USER_DATA_PATH + "/" + fileName,
            success: function (res) {
              console.log("保存成功！", res)

              // 打开文档
              wx.openDocument({
                filePath: wx.env.USER_DATA_PATH + "/" + fileName,
                showMenu: true,
                success: function (res) {
                  console.log(wx.env.USER_DATA_PATH + '/' + fileName)
                  console.log('打开文档成功:', res)
                },
                fail: function (res) {
                  console.log(wx.env.USER_DATA_PATH + '/' + fileName)
                  console.log('打开失败', res);
                }
              })
            },
            fail: function (res) {
              console.log("打开失败", res)
            }
          });

        }
      }
    })
  }


})